// 书籍
const mongoose = require('mongoose');
const moment = require('moment');

const bookSchema = new mongoose.Schema({
    id: {
        type: Number,
        unique: true
    },
    title: {
        type: String,
        required: [true, '请提供书名']
    },
    author: {
        type: String,
        required: [true, '请提供作者']
    },
    genre: {
        type: String
    },
    publishedYear: {
        type: Number
    },
    createTime: String, // 存储格式化后的字符串
    createdAt: {
        type: Date,
        default: Date.now
    }
});

// 前置钩子：在文档保存前格式化时间
bookSchema.pre('save', async function (next) {
    if (!this.createTime) {
        // 将当前时间格式化为 "YYYY-MM-DD HH:mm:ss"
        this.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
    }
    next();
});

module.exports = mongoose.model('Book', bookSchema);